/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Controller.InputChecker;
import Entity.Owner;
import Entity.Pet;
import Entity.Veterinarian;
import Services.EmployeeService;
import Services.OwnerService;
import Services.PetService;
import Services.VeterinarianService;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author arch
 */
public class FSearcher extends javax.swing.JFrame {

  /**
   * Creates new form FSearcher
   */
    
  private EntityManagerFactory emf=null;
  public FSearcher() {
    initComponents();
    
    chbVeterinarians = new JCheckBox();
    chbOwners = new JCheckBox();
    chbPets = new JCheckBox();
    chbSSN = new JCheckBox();
    
    pets = new ArrayList();
    owners = new ArrayList();
    veterinarians = new ArrayList();
    
    dialogPet = new DPet(this, true);
    dialogOwner = new DOwner(this, true);
    dialogVeterinarian = new DVeterinarian(this, true);
    
    init();
    selectedTypes = 4;
    emf=Persistence.createEntityManagerFactory("HPVASPU");
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    chbOwners = new javax.swing.JCheckBox();
    lSearchResult = new javax.swing.JLabel();
    jSeparator1 = new javax.swing.JSeparator();
    chbSSN = new javax.swing.JCheckBox();
    bNewPet = new javax.swing.JButton();
    chbVeterinarians = new javax.swing.JCheckBox();
    scrollPane = new javax.swing.JScrollPane();
    pResult = new javax.swing.JPanel();
    tfSearch = new javax.swing.JTextField();
    bSearch = new javax.swing.JButton();
    bNewOwner = new javax.swing.JButton();
    bNewVeterinarian = new javax.swing.JButton();
    chbPets = new javax.swing.JCheckBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    chbOwners.setSelected(true);
    chbOwners.setText("Owners");
    chbOwners.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        chbOwnersActionPerformed(evt);
      }
    });

    lSearchResult.setText("Search result:");

    chbSSN.setSelected(true);
    chbSSN.setText("By SSN");
    chbSSN.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        chbSSNActionPerformed(evt);
      }
    });

    bNewPet.setText("New Pet");
    bNewPet.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bNewPetActionPerformed(evt);
      }
    });

    chbVeterinarians.setSelected(true);
    chbVeterinarians.setText("Veterinarians");
    chbVeterinarians.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        chbVeterinariansActionPerformed(evt);
      }
    });

    pResult.setLayout(new java.awt.GridLayout(1, 0));
    scrollPane.setViewportView(pResult);

    tfSearch.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        tfSearchActionPerformed(evt);
      }
    });

    bSearch.setText("Search");
    bSearch.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bSearchActionPerformed(evt);
      }
    });

    bNewOwner.setText("New Owner");
    bNewOwner.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bNewOwnerActionPerformed(evt);
      }
    });

    bNewVeterinarian.setText("New Veterinarian");
    bNewVeterinarian.setFocusPainted(false);
    bNewVeterinarian.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bNewVeterinarianActionPerformed(evt);
      }
    });

    chbPets.setSelected(true);
    chbPets.setText("Pets");
    chbPets.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        chbPetsActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(scrollPane)
      .addComponent(jSeparator1)
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(bNewVeterinarian)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(bNewOwner)
            .addGap(18, 18, 18)
            .addComponent(bNewPet))
          .addGroup(layout.createSequentialGroup()
            .addGap(140, 140, 140)
            .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(bSearch)))
        .addGap(0, 165, Short.MAX_VALUE))
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addGap(181, 181, 181)
            .addComponent(chbPets)
            .addGap(18, 18, 18)
            .addComponent(chbOwners)
            .addGap(18, 18, 18)
            .addComponent(chbVeterinarians)
            .addGap(18, 18, 18)
            .addComponent(chbSSN))
          .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(lSearchResult)))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(bNewVeterinarian)
          .addComponent(bNewOwner)
          .addComponent(bNewPet))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(bSearch))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(chbPets)
          .addComponent(chbOwners)
          .addComponent(chbVeterinarians)
          .addComponent(chbSSN))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(lSearchResult)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 386, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void tfSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfSearchActionPerformed
    bSearchActionPerformed(evt);
  }//GEN-LAST:event_tfSearchActionPerformed

  private void bSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSearchActionPerformed

    if (selectedTypes == 0) {
      JOptionPane.showMessageDialog(this, "No targets to search", "Warning", JOptionPane.WARNING_MESSAGE);
      return;
    }

    inputSearch = tfSearch.getText();

    if (!InputChecker.check(inputSearch)) {
      JOptionPane.showMessageDialog(this, "Invalid search criteria", "Warning", JOptionPane.WARNING_MESSAGE);
      return;
    }

    inputSearch = inputSearch.toLowerCase();

    pets.clear();
    owners.clear();
    veterinarians.clear();

    // Aqui' se debe llamar al DAO correspondiente para cada tipo
    // a los srcPets, srcOwners, srcVeterinarians se les debe asignar el resultado del DAO
    
    // ----------------------------------------------------------------
    // Obtener Lista de resultados que concuerdan la clave de bu'squeda
    // ----------------------------------------------------------------
    PetService ps=new PetService(emf);
    srcPets=ps.findPetEntities();
    OwnerService os=new OwnerService(emf);
    srcOwners=os.findOwnerEntities();
    VeterinarianService vs=new VeterinarianService(emf);
    srcVeterinarians=vs.findVeterinarianEntities();

    if (inputSearch.length() > 0) {
      if (chbPets.isSelected()) {
        for (Pet p : srcPets) {
          if (p.getName().toLowerCase().contains(inputSearch)) {
            pets.add(p);
          }
        }
      }
      if (chbOwners.isSelected() || chbSSN.isSelected()) {
        for (Owner o : srcOwners) {
          if ((chbOwners.isSelected() && o.getName().toLowerCase().contains(inputSearch))
            || (chbSSN.isSelected() && inputSearch.equals(o.getSSN()))) {
            owners.add(o);
          }
        }
      }
      if (chbVeterinarians.isSelected()) {
        for (Veterinarian v : srcVeterinarians) {
          if (v.getName().toLowerCase().contains(inputSearch)) {
            veterinarians.add(v);
          }
        }
      }
    }
    int n = pets.size() + owners.size() + veterinarians.size();

    pResult.removeAll();
    pResult.revalidate();
    pResult.setLayout(new GridLayout(Math.max(10, n), 1));

    int parity = 0;

    for (int i = 0; i < pets.size(); ++i, ++parity) {

      final Pet op = pets.get(i);
      final JButton b = new JButton(op.getName() + " - Pet");
      b.setForeground(Color.BLUE);
      b.setFocusPainted(false);
      b.setBackground(light);
      if ((parity & 1) != 0) {
        b.setBackground(dark);
      }
      b.addActionListener(new ActionListener() {
        Pet p = op;
        public void actionPerformed(ActionEvent e) {
          dialogPet.set(p);
          dialogPet.setVisible(true);
        }
      });
      pResult.add(b);
    }

    for (int i = 0; i < owners.size(); ++i, ++parity) {

      final Owner ow = owners.get(i);
      final JButton b = new JButton(ow.getName() + " - Owner");
      b.setForeground(Color.BLUE);
      b.setFocusPainted(false);
      b.setBackground(light);
      if ((parity & 1) != 0) {
        b.setBackground(dark);
      }
      b.addActionListener(new ActionListener() {
        Owner o = ow;
        public void actionPerformed(ActionEvent e) {
          dialogOwner.set(o);
          dialogOwner.setVisible(true);
        }
      });
      pResult.add(b);
    }

    for (int i = 0; i < veterinarians.size(); ++i, ++parity) {

      final Veterinarian ov = veterinarians.get(i);
      final JButton b = new JButton(ov.getName() + " - Veterinarian");
      b.setForeground(Color.BLUE);
      b.setFocusPainted(false);
      b.setBackground(light);
      if ((parity & 1) != 0) {
        b.setBackground(dark);
      }
      b.addActionListener(new ActionListener() {
        Veterinarian v = ov;
        public void actionPerformed(ActionEvent e) {
          // Mostrar la vista de la mascota
          dialogVeterinarian.set(v);
          dialogVeterinarian.setVisible(true);
        }
      });
      pResult.add(b);
    }
    lSearchResult.setText(n + " Matching result(s)");
    pResult.revalidate();
    pResult.repaint();
  }//GEN-LAST:event_bSearchActionPerformed

  private void chbPetsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbPetsActionPerformed
    
    chbPets.setSelected(!chbPets.isSelected());
    if (chbPets.isSelected()) ++selectedTypes;
    else --selectedTypes;
    bSearchActionPerformed(new java.awt.event.ActionEvent(new Object(){}, 0, ""));
  }//GEN-LAST:event_chbPetsActionPerformed

  private void chbVeterinariansActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbVeterinariansActionPerformed
    
    chbVeterinarians.setSelected(!chbVeterinarians.isSelected());
    if (chbVeterinarians.isSelected()) ++selectedTypes;
    else --selectedTypes;
    bSearchActionPerformed(new java.awt.event.ActionEvent(new Object(){}, 0, ""));
  }//GEN-LAST:event_chbVeterinariansActionPerformed

  private void chbSSNActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbSSNActionPerformed
    
    chbSSN.setSelected(!chbSSN.isSelected());
    if (chbSSN.isSelected()) ++selectedTypes;
    else --selectedTypes;
    bSearchActionPerformed(new java.awt.event.ActionEvent(new Object(){}, 0, ""));
  }//GEN-LAST:event_chbSSNActionPerformed

  private void chbOwnersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbOwnersActionPerformed
    
    chbOwners.setSelected(!chbOwners.isSelected());
    if (chbOwners.isSelected()) ++selectedTypes;
    else --selectedTypes;
    bSearchActionPerformed(new java.awt.event.ActionEvent(new Object(){}, 0, ""));
  }//GEN-LAST:event_chbOwnersActionPerformed

  private void bNewVeterinarianActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNewVeterinarianActionPerformed
    
    dialogVeterinarian.set(null);
    dialogVeterinarian.setVisible(true);
  }//GEN-LAST:event_bNewVeterinarianActionPerformed

  private void bNewOwnerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNewOwnerActionPerformed
    
    
    dialogOwner.set(null);
    dialogOwner.setVisible(true);
  }//GEN-LAST:event_bNewOwnerActionPerformed

  private void bNewPetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNewPetActionPerformed
    
    dialogPet.set(null);
    dialogPet.setVisible(true);
  }//GEN-LAST:event_bNewPetActionPerformed

  public void init() {
    
    selectedTypes = 4;
    
    chbVeterinarians.setSelected(true);
    chbOwners.setSelected(true);
    chbPets.setSelected(true);
    chbSSN.setSelected(true);
    
    pets.clear();
    owners.clear();
    veterinarians.clear();
    
    tfSearch.setText("");
    inputSearch = "";
  }
  
  /**
   * @param args the command line arguments
   */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(FSearcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(FSearcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(FSearcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(FSearcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    
    final EntityManagerFactory emf1;
    emf1=Persistence.createEntityManagerFactory("HPVASPU");
    try {
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } 
    catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {}
    // enable anti-aliased text:
    System.setProperty("awt.useSystemAAFontSettings","on");
    System.setProperty("swing.aatext", "true");
    
    final JDialog dLogin = new JDialog();
    dLogin.setLayout(new GridLayout(3, 1));
    dLogin.setTitle("LogIn");
    
    final JTextField tfUsername = new JTextField(20);
    
    JPanel pUsername = new JPanel(new FlowLayout(FlowLayout.LEFT));
    pUsername.add(new JLabel("username: "));
    pUsername.add(tfUsername);
    
    final JPasswordField tfPassword = new JPasswordField(20);
    
    JPanel pPassword = new JPanel(new FlowLayout(FlowLayout.LEFT));
    pPassword.add(new JLabel("password: "));
    pPassword.add(tfPassword);
    
    JPanel pButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    
    JButton bLogin = new JButton("Login");
    bLogin.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        EmployeeService es=new EmployeeService(emf1);
        String pass = new String(tfPassword.getPassword());
        boolean ok =es.login(tfUsername.getText(), pass);
        
        if (ok) {
          dLogin.setVisible(false);
          FSearcher f = new FSearcher();
          f.setTitle("HPVAS");
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.pack();
          f.setLocationRelativeTo(null);
          f.setVisible(true);
        } else {
          JOptionPane.showMessageDialog(dLogin, "Invalid username or password", "Warning", JOptionPane.WARNING_MESSAGE);
        }
      }
    });
    
    JButton bExit = new JButton("Exit");
    bExit.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        System.exit(0);
      }
    });
    
    pButtons.add(bLogin);
    pButtons.add(bExit);
    
    dLogin.add(pUsername);
    dLogin.add(pPassword);
    dLogin.add(pButtons);
    dLogin.setSize(330, 130);
    dLogin.setLocationRelativeTo(null);
    dLogin.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dLogin.setVisible(true);
  }
  
    // Guarda los resultados de la bu'squeda
  List<Pet> pets;
  List<Owner> owners;
  List<Veterinarian> veterinarians;
  
  String inputSearch;
  int selectedTypes;
  
  DPet dialogPet;
  DOwner dialogOwner;
  DVeterinarian dialogVeterinarian;
          
  Color light = new Color(230, 230, 230);
  Color dark = new Color(243, 243, 243);
  
  List<Pet> srcPets;
  List<Owner> srcOwners;
  List<Veterinarian> srcVeterinarians;
  
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton bNewOwner;
  private javax.swing.JButton bNewPet;
  private javax.swing.JButton bNewVeterinarian;
  private javax.swing.JButton bSearch;
  private javax.swing.JCheckBox chbOwners;
  private javax.swing.JCheckBox chbPets;
  private javax.swing.JCheckBox chbSSN;
  private javax.swing.JCheckBox chbVeterinarians;
  private javax.swing.JSeparator jSeparator1;
  private javax.swing.JLabel lSearchResult;
  private javax.swing.JPanel pResult;
  private javax.swing.JScrollPane scrollPane;
  private javax.swing.JTextField tfSearch;
  // End of variables declaration//GEN-END:variables
}
